package com.example.suntest.utils;

import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.Field;

/**
 * @version 1.0
 * @Package: com.at.mrp.bll.util
 * @ClassName: BeanCopyUtils
 * @Author: sgq
 * @Date: 2024/12/4 19:24
 * @Description: TODD
 */
public class BeanCopyUtils {
    public static <T> T copyPropertiesIgnoreNull(Object source, Class<T> targetClass) {
        try {
            T target = targetClass.newInstance();
            Field[] fields = source.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(source);
                if (value != null) {
                    BeanUtils.copyProperty(target, field.getName(), value);
                }
            }
            return target;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
